package com.funny.stock.user.service;

import com.alibaba.fastjson.JSON;
import com.funny.stock.base.redis.RestTemplateTool;
import com.funny.stock.base.util.CommonUtils;
import com.funny.stock.user.util.UserSecurityUtil;
import com.funny.stock.user.vo.ExceptionMsg;
import com.funny.stock.user.vo.RobotMessage;
import com.funny.stock.user.vo.SysUserVO;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * @author pengl
 * @date 2020/7/17
 */
@Component
public class WXRobotMsgService implements RobotMsgService {
    private static final Logger logger = LoggerFactory.getLogger(WXRobotMsgService.class);

    @Autowired
    TaskExecutor taskExecutor;

    @Autowired
    ApplicationConfig applicationConfig;

    @Autowired
    RestTemplateTool restTemplateTool;

    @Value("${config.wxrobot.url}")
    String wxMsgUrl;

    @Override
    public void sendMessage(RobotMessage message) {
        if(!applicationConfig.isProductEnv())
            return;

        if(StringUtils.isEmpty(wxMsgUrl))
            return;

//        taskExecutor.execute(() -> {
//            try {
//                startSendRobotMsg(message);
//            }catch (Exception e1){
//                logger.error("startSendRobotMsg fail,{}",e1.getMessage());
//            }
//        });
    }

    private void startSendRobotMsg(RobotMessage message) {
        logger.info("开始发送WX消息");
        Map<String,Object> msgMap = new HashMap<>();

        Map<String,Object> contentMap = new HashMap<>();

        if(message.getContent() instanceof ExceptionMsg){
            ExceptionMsg msg = (ExceptionMsg) message.getContent();
            String text = getMarkdownText(msg);
            contentMap.put("content", text);

            msgMap.put("msgtype","markdown");
            msgMap.put("markdown",contentMap);
        }else{
            if(message.getContent() instanceof String){
                contentMap.put("content", message.getContent());
            }else{
                contentMap.put("content", JSON.toJSONString(message.getContent()));
            }

            msgMap.put("msgtype","text");
            msgMap.put("text",contentMap);
        }

//        String result = restTemplateTool.postJsonForObject(wxMsgUrl, msgMap, String.class);
//        logger.info("发送WX消息结果,{}",result);
    }

    private String getMarkdownText(ExceptionMsg exceptionMsg){
        String template = "实时异常上报，请注意。\n" +
                ">Profile: <font color=\"comment\">%s</font>\n" +
                ">异常ID: <font color=\"comment\">%s</font>\n" +
                ">异常类型: <font color=\"comment\">%s</font>\n" +
                ">接口路径: <font color=\"comment\">%s</font>\n" +
                ">用户ID: <font color=\"comment\">%s</font>\n" +
                ">异常详情: \n" +
                "%s\n";

        String format = String.format(template, applicationConfig.isProductEnv() ? "prod" : "dev",
                exceptionMsg.getId(),exceptionMsg.getExceptionName(), exceptionMsg.getPath(), exceptionMsg.getUserId(),exceptionMsg.getDetail());


        return format;
    }

    @Override
    public void sendExceptionMessage(String path, Throwable e) {
        if(!applicationConfig.isProductEnv())
            return;

        if(StringUtils.isEmpty(wxMsgUrl))
            return;
        SysUserVO user = UserSecurityUtil.getUser();
        final String loginAccount = user == null ? null : user.getLoginAccount();

        taskExecutor.execute(() -> {
            try {
                RobotMessage robotMessage = createExceptionMsg(path,loginAccount, e);
                startSendRobotMsg(robotMessage);
            }catch (Exception e1){
                logger.error("sendExceptionMessage fail,{}",e1.getMessage());
            }
        });
    }


    private RobotMessage createExceptionMsg(String path,String loginAccount,Throwable e){
        RobotMessage message = new RobotMessage();
        ExceptionMsg exceptionMsg = new ExceptionMsg();

        exceptionMsg.setUserId(loginAccount);
//        exceptionMsg.setCreateTime(new Date());
        if(e != null) {
            exceptionMsg.setMessage(e.getLocalizedMessage());
            exceptionMsg.setExceptionName(e.getClass().getName());
            String traceInfo = CommonUtils.getStackTraceInfo(e);
            exceptionMsg.setFullDetail(traceInfo);
            exceptionMsg.setDetail(getMsgDesc(traceInfo));
        }

        exceptionMsg.setPath(path);
        message.setContent(exceptionMsg);
        return message;
    }

    private String getMsgDesc(String msg){
        if(msg.length() <= 500)
            return msg;

        StringBuilder sb = new StringBuilder();
        String[] split = msg.split("\n");
        if(split.length != 0)
            sb.append(split[0]);

        for (int i = 1; i < split.length; i++) {
            if(split[i].contains("com.funny.stock") &&
                    !(split[i].contains("MyFilterSecurityInterceptor") || split[i].contains("doFilter"))) {
                sb.append(split[i]);
                sb.append(";");
            }
        }

        String content = sb.toString();
        if(content.length() > 500)
            content = content.substring(0,500);

        return content;
    }
}
